<template>
	<view class="payment">
		<view class='pay-money'>
			<view class='left'>{{currentPayType == 1 ? '定金': '尾款'}}</view>
			<view class='right'>￥{{money}}</view>
		</view>
		<view class='pay-way'>
			<view class='w-name'>支付方式</view>
			<view class='select-list'>
				<view class='select-item'>
					<image class='img1' @click='selectItem("02")' mode='widthFix'
						:src="'https://pfmotortest.hb4oss.xstore.ctyun.cn/appstatic/img/'+ (payType === '02' ? '': 'un' )+ 'choose_icon.png'">
					</image>
					<image class='img2' mode='widthFix'
						src='https://pfmotortest.hb4oss.xstore.ctyun.cn/appstatic/img/pay-wechat.png'>
					</image>
					<view class='text'>微信支付</view>
				</view>
				<!-- #ifdef APP-PLUS||H5 -->
				<view class='select-item'>
					<image class='img1' @click='selectItem("01")' mode='widthFix'
						:src="'https://pfmotortest.hb4oss.xstore.ctyun.cn/appstatic/img/'+ (payType === '01' ? '': 'un') + 'choose_icon.png'">
					</image>
					<image class='img2' mode='widthFix'
						src='https://pfmotortest.hb4oss.xstore.ctyun.cn/appstatic/img/pay-alipay.png'>
					</image>
					<view class='text'>支付宝支付</view>
				</view>
				<!-- #endif -->
			</view>
		</view>
		<!-- 五期,定金校验时间 -->
		<view class='pay-btn' @click="payOrderTime" v-if="currentPayType==1">确认支付</view>
		<view class='pay-btn' @click="payOrder" v-else>确认支付</view>
		<!-- 四期 -->
		<!-- <view class='pay-btn' @click="payOrder">确认支付</view> -->
	</view>

</template>

<script>
	const app = getApp();
	const util = require('@utils/util.js');
	const network = require('@manager/network-manager.js');
	const dialog = require('@utils/dialog.js');
	import dayjs from 'dayjs'
	export default {
		data() {
			return {
				payType: null,
				orderId: '',
				id: null,
				currentPayType: null,
				money: null,
				hide: false,
				from: null,
				expireTime: '',
				diff: 0
			}
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			this.id = options.id
			this.currentPayType = options.currentPayType
			this.money = options.money
			this.from = options.from
			if (options.expireTime) {
				this.expireTime = options.expireTime
			}
			// if (options.payType) this.payType = (options.payType == 1 ? '02' : '01')

		},
		onShow: function() {
			if (this.hide && (this.payType == '02')) {
				this.pollingOrderStatus()
			}
		},
		onHide() {
			this.hide = true
		},
		methods: {

			selectItem(current) {
				if (this.payType == current) return
				this.payType = current
			},

			payOrderTime() {
				var that = this;
				var uri = app.globalData.config.interfaces
					.URL_SYS_API_GETBEIJINGTIME; ///levc-sys/sendMessage/updateLevcMessageUserReady
				var params = {};
				network.get(uri, params, 'json').then(res => {
					if (res.code == 200) {
						console.log("已读", JSON.stringify(res));
						var nowTime = res.data
						that.diff = dayjs(that.expireTime).diff(dayjs(nowTime))
						if (that.diff < 0) {
							uni.showToast({
								title: '订单已过期',
								duration: 3000,
								icon: 'none'
							})
						} else {
							that.payOrder()
						}
					} else {
						uni.showToast({
							title: res.message,
							duration: 3000,
							icon: 'none'
						})
					}

				}).catch(res => {
					uni.showToast({
						title: res.errMsg,
						duration: 3000,
						icon: 'none'
					})
					console.error(res);
				});
			},

			payOrder() {
				if (!this.payType) {
					uni.showToast({
						title: '请先选择支付方式',
						icon: 'none',
						duration: 2000
					})
					return
				}
				var that = this
				//#ifdef APP-PLUS||H5
				let params = {
					paymentChannel: this.payType,
					outTradeNo: this.id,
					goodsDescription: `派方摩托车${this.currentPayType == 1 ? '定金': '订单'}支付`,
					paymentChannelSubclass: this.payType,
					// openid: uni.getStorageSync('openId')
				};
				let url = app.globalData.config.interfaces.URL_PAYMENT_ALL; // wx.navigateTo({
				//   url: '/module_my/pages/car/paySuccess/paySuccess?id=' + this.data.id
				// })

				network.post(url, params, 'json', null, true).then(res => {
					console.log(res)
					let data = {
						appid: res.appId,
						noncestr: res.nonceStr,
						package: res.package,
						partnerid: res.partnerId,
						prepayid: res.prepayId,
						timestamp: res.timeStamp + '',
						sign: res.sign
					}

					let order = params.paymentChannel === '01' ? (res.orderString + '&sign=' + res.sign) : data;
					console.log("submit order:" + params.paymentChannel === '01' ? order : JSON.stringify(order));
					if (res) {
						uni.requestPayment({
							provider: params.paymentChannel === '01' ? 'alipay' : 'wxpay',
							orderInfo: order,
							success: function(res) {
								console.log("requestPayment success" + JSON.stringify(res));
								if (res.errMsg === "requestPayment:ok") {
									that.hide = false
									that.back()
								}
							},
							fail: function(err) {
								console.log("requestPayment err" + JSON.stringify(res));
								// dialog.toast("支付失败");
								// that.hide = false
								that.checkOrderStatus()
							},
							complete: function(e) {
								console.log("requestPayment complete" + JSON.stringify(e));

							}
						});
					}
				})
				//#endif
				//#ifdef MP-WEIXIN
				let params = {
					paymentChannel: this.payType,
					openid: uni.getStorageSync('openId'),
					outTradeNo: this.id,
					goodsDescription: `派方摩托车${this.currentPayType == 1 ? '定金': '订单'}支付`,
					paymentChannelSubclass: this.payType,
				};
				let url = app.globalData.config.interfaces.URL_PAYMENT;

				network.post(url, params, 'json').then(res => {
					console.log(res)
					let data = {
						appid: res.appId,
						noncestr: res.nonceStr,
						package: res.package,
						partnerid: res.partnerId,
						prepayid: res.prepayId,
						timestamp: res.timeStamp + '',
						sign: res.sign
					}

					let order = params.paymentChannel === '01' ? (res.orderString + '&sign=' + res.sign) :
						data;
					console.log("submit order:" + params.paymentChannel === '01' ? order : JSON.stringify(
						order));
					if (res) {
						uni.requestPayment({
							appid: res.appId,
							timeStamp: res.timeStamp + '',
							nonceStr: res.nonceStr,
							package: res.package,
							paySign: res.paySign,
							signType: 'MD5',
							success: function(res) {
								console.log("requestPayment success" + JSON.stringify(res));
								if (res.errMsg === "requestPayment:ok") {
									that.hide = false
									that.back()
								}
							},
							fail: function(err) {
								console.log("requestPayment err" + JSON.stringify(res));
								// that.hide = false
								// setTimeout(() => {
								// 	wx.showToast({
								// 		title: "支付失败",
								// 		duration: 3000,
								// 		icon: 'none'
								// 	});
								// }, 500);
								that.checkOrderStatus()
							},
							complete: function(e) {
								console.log("requestPayment complete" + JSON.stringify(e));
							}
						})
					}
				})
				//#endif

			},

			back() {
				console.log('this.from', this.from)
				if (this.from == 'orderList') {
					uni.redirectTo({
						url: '/module_my/pages/orderList/orderList'
					})
				} else {
					uni.navigateBack({
						delta: 1
					});
				}
			},

			// 查询一遍订单状态 针对支付成功报error
			checkOrderStatus() {
				let url = app.globalData.config.interfaces.URL_GET_CARORDER_ORDER
				let params = {
					"id": this.id
				};
				network.get(url, params, 'form').then(res => {
					if (res.code == 200) {
						if (Number(res.data.orderFlag) > 1) {
							this.back()
							this.hide = false
						} else {
							dialog.toast("支付失败")
						}
					}
				}).catch(error => {
					uni.showToast({
						title: error.message,
						duration: 2000,
						icon: 'error'
					})
				})
			},

			// 轮询查询订单支付状态
			pollingOrderStatus() {
				let timer = setInterval(() => {
					if (!this.hide) return
					let url = app.globalData.config.interfaces.URL_GET_CARORDER_ORDER
					let params = {
						"id": this.id
					};
					network.get(url, params, 'form').then(res => {
						if (res.code == 200) {
							if (Number(res.data.orderFlag) > 1) {
								clearInterval(timer)
								this.back()
								this.hide = false
							}
						}
					})
				}, 1000)
			},

		},
	}
</script>

<style>
	@import "./payment.css";
</style>
